﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.Documents;
using Google.GData.Client;
using Google.GData.Documents;

namespace my_google_doc_online
{
    public partial class MainForm : Form
    {
        //private MyMethod m = new MyMethod();
        private LoginForm lf = new LoginForm();
        //private List<Document> all = new List<Document>();
        //private TextDocumentQuery wordquery = new TextDocumentQuery();
        //private SpreadsheetQuery exlquery = new SpreadsheetQuery();
        //private PresentationsQuery pptquery = new PresentationsQuery();

        public MainForm()
        {
            InitializeComponent();
        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {
            DialogResult r = lf.ShowDialog();

            if (r == DialogResult.OK)
            {
                listBox1.Visible = true;
                loginMenuItem.Enabled = false;
                logoutMenuItem.Enabled = true;
                UpdateDocList();
                toolStripStatusLabel1.Text = "已登录";
            }
        }

        private void 注销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lf.m.Logout();
            listBox1.Visible = false;
            loginMenuItem.Enabled = true;
            logoutMenuItem.Enabled = false;
            listView1.Items.Clear();
            FoldertreeView.Nodes.Clear();
            toolStripStatusLabel1.Text = "未登录";
        }

        public void UpdateDocList()
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            listView1.Clear();
            FoldertreeView.Nodes.Clear();
            listView1.Columns.Add("标题", 280, HorizontalAlignment.Left);
            listView1.Columns.Add("创建时间", 130, HorizontalAlignment.Left);
            listView1.Columns.Add("修改时间", 130, HorizontalAlignment.Left);
            listView1.Columns.Add("作者", 100, HorizontalAlignment.Center);
            //RequestSettings settings = new RequestSettings("my_google_doc_online", lf.Credentials);
            //settings.AutoPaging = true;
            //settings.PageSize = 100;
            //lf.m.request = new DocumentsRequest(settings);
            //TextDocumentQuery wordquery = new TextDocumentQuery();
            //SpreadsheetQuery exlquery = new SpreadsheetQuery();


            Feed<Document> feeds = lf.m.request.GetEverything();
            //var other = lf.m.request.MoveDocumentTo(feeds.Entries[0], );
            //feeds.Entries = feeds.Entries.OrderByDescending(s => s.DocumentEntry.Published);

            TreeNode noFolder = new TreeNode("其他文件");
            FoldertreeView.Nodes.Add(noFolder);

            //foreach (Document entry in feeds.Entries)
            //{
            //    all.Add(entry);
            //}

            //DocumentsFeed feed = lf.m.GetDocs();
            //listView1.Columns.Add("标题", 260, HorizontalAlignment.Left);
            //listView1.Columns.Add("修改时间", 130, HorizontalAlignment.Left);
            //listView1.Columns.Add("作者", 100, HorizontalAlignment.Center);

            foreach (Document entry in feeds.Entries)
            {
                if (entry.Type != Document.DocumentType.Folder)
                {
                    ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                    item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                    item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                    item.SubItems.Add(entry.Author);
                    item.Tag = entry;
                    listView1.Items.Add(item);
                }
                else if (entry.Type == Document.DocumentType.Folder)
                {
                    //获取文件夹根节点
                    if (entry.ParentFolders.Count == 0)
                    {
                        TreeNode n = AddToTreeView(FoldertreeView.Nodes, entry);
                        AddAllChildren(n.Nodes, entry);
                        FoldertreeView.ExpandAll();
                    }
                }
            }
        }

        private static TreeNode AddToTreeView(TreeNodeCollection parent, Document doc)
        {
            TreeNode node = new TreeNode(doc.Title);
            node.Tag = doc;
            parent.Add(node); //添加该节点
            return node;
        }

        private void AddAllChildren(TreeNodeCollection col, Document entry)
        {
            Feed<Document> feeds = lf.m.request.GetFolders();

            foreach (Document d in feeds.Entries)
            {
                //判断d是否为entry子文件夹
                if (d.ParentFolders.Contains(entry.Self))
                {
                    TreeNode n = AddToTreeView(col, d);
                    AddAllChildren(n.Nodes, d);
                }
            }
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                //获取用户选中项的对象信息
                Document entry = (Document) listView1.SelectedItems[0].Tag;
                Process.Start(entry.DocumentEntry.AlternateUri.ToString());
            }
        }

        private void uploadBtn_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            openFileUpload.ShowDialog();
            string filename = openFileUpload.FileName;

            if (filename == "")
            {
                MessageBox.Show("未选择文件", "未上传", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            lf.m.service.UploadDocument(filename, null);
            UpdateDocList();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void downloadBtn_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择下载文件", "请选择", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ListViewItem items = listView1.SelectedItems[0];

            Document d = items.Tag as Document;
            saveFileDownload.FileName = d.DocumentEntry.Title.Text;

            Document.DownloadType type;

            switch (d.Type)
            {
                case Document.DocumentType.Presentation:
                    saveFileDownload.Filter = "Powerpoint|*.ppt";
                    type = Document.DownloadType.ppt;
                    break;
                case Document.DocumentType.Spreadsheet:
                    saveFileDownload.Filter = "Excel|*.xls";
                    type = Document.DownloadType.xls;
                    break;
                default:
                    saveFileDownload.Filter = "Microsoft Word|*.doc";
                    type = Document.DownloadType.doc;
                    break;
            }

            if (saveFileDownload.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = saveFileDownload.OpenFile();

                try
                {
                    if (file != null)
                    {
                        int nBytes = 2048;
                        int count = 0;
                        Byte[] arr = new Byte[nBytes];

                        do
                        {
                            count = stream.Read(arr, 0, nBytes);
                            file.Write(arr, 0, count);
                        } while (count > 0);
                        file.Flush();
                        file.Close();
                    }
                    stream.Close();
                    MessageBox.Show("下载成功", "下载完成", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("下载失败：" + ex.Message, "下载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw;
                }
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            UpdateDocList();
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                pDF文件ToolStripMenuItem.Visible = true;
                hTML文件ToolStripMenuItem.Visible = true;
                tXT文件ToolStripMenuItem.Visible = true;
                pDF文件ToolStripMenuItem.Enabled = true;
                hTML文件ToolStripMenuItem.Enabled = true;
                tXT文件ToolStripMenuItem.Enabled = true;

                ListViewItem item = listView1.FocusedItem;
                if (item.Tag != null)
                {
                    Document d = item.Tag as Document;

                    switch (d.Type)
                    {
                        case Document.DocumentType.Spreadsheet:
                            rTFMenuItem.Visible = false;
                            cSVMenuItem.Visible = true;
                            rTF文件ToolStripMenuItem.Visible = false;
                            cSV文件ToolStripMenuItem.Visible = true;
                            rTF文件ToolStripMenuItem.Enabled = false;
                            cSV文件ToolStripMenuItem.Enabled = true;
                            break;
                        case Document.DocumentType.Document:
                            rTFMenuItem.Visible = true;
                            cSVMenuItem.Visible = false;
                            rTF文件ToolStripMenuItem.Visible = true;
                            cSV文件ToolStripMenuItem.Visible = false;
                            rTF文件ToolStripMenuItem.Enabled = true;
                            cSV文件ToolStripMenuItem.Enabled = false;
                            break;
                        default:
                            rTFMenuItem.Visible = false;
                            cSVMenuItem.Visible = false;
                            cSV文件ToolStripMenuItem.Visible = false;
                            rTF文件ToolStripMenuItem.Visible = false;
                            break;
                    }
                }

                openfileOnlineMenuItem.Enabled = true;
                downloadMenuItem.Enabled = true;
                deleteMenuItem.Enabled = true;
                exportToolStripMenuItem.Enabled = true;
                exportToolStripMenuItem.Enabled = true;
            }
            else
            {
                pDF文件ToolStripMenuItem.Enabled = false;
                hTML文件ToolStripMenuItem.Enabled = false;
                tXT文件ToolStripMenuItem.Enabled = false;

                openfileOnlineMenuItem.Enabled = false;
                downloadMenuItem.Enabled = false;
                deleteMenuItem.Enabled = false;
                exportToolStripMenuItem.Enabled = false;
                exportToolStripMenuItem.Enabled = false;
            }
        }

        private string docimage(Document entry)
        {
            string imageKey = "";
            if (entry.DocumentEntry.IsDocument)
            {
                imageKey = "icon_9_document_list.png";
            }
            else if (entry.DocumentEntry.IsSpreadsheet)
            {
                imageKey = "icon_9_spreadsheet_list.png";
            }
            else if (entry.DocumentEntry.IsPresentation)
            {
                imageKey = "icon_9_presentation_list.png";
            }
            else if (entry.DocumentEntry.IsFolder)
            {
                imageKey = "icon_8_collection_list.png";
            }
            return imageKey;
        }

        private void FoldertreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            Feed<Document> feeds = lf.m.request.GetEverything();

            TreeNode node = e.Node;
            Document d = node.Tag as Document;
            listView1.Items.Clear();

            if (e.Node.Text == "其他文件")
            {
                foreach (Document entry in feeds.Entries)
                {
                    if (entry.ParentFolders.Count == 0)
                    {
                        ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                        item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                        item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                        item.SubItems.Add(entry.Author);
                        item.Tag = entry;
                        listView1.Items.Add(item);
                    }
                }
            }
                //if (d != null)
            else if (d != null)
            {
                string parent = d.DocumentEntry.EditUri.ToString();

                foreach (Document entry in feeds.Entries)
                {
                    if (entry.ParentFolders.Count > 0 && entry.ParentFolders[0] == parent)
                    {
                        ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                        item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                        item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                        item.SubItems.Add(entry.Author);
                        item.Tag = entry;
                        listView1.Items.Add(item);
                    }
                }
            }
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            listView1.Items.Clear();
            Feed<Document> feeds = lf.m.request.GetEverything();
            foreach (Document entry in feeds.Entries)
            {
                if (entry.DocumentEntry.Title.Text.Contains(searchTextBox.Text))
                {
                    ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                    item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                    item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                    item.SubItems.Add(entry.Author);
                    item.Tag = entry;
                    listView1.Items.Add(item);
                }
            }
            searchTextBox.Text = "";
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (listView1.SelectedItems.Count > 0)
            {
                Document entry = (Document) listView1.SelectedItems[0].Tag;
                DialogResult result = MessageBox.Show("确定删除" + entry.DocumentEntry.Title.Text + "吗?", "确认删除",
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    try
                    {
                        entry.DocumentEntry.Delete();
                        UpdateDocList();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("删除失败: " + ex.Message, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择文件 ", "无法删除", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void listViewMenuStrip1_Opened(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = listView1.FocusedItem;
                if (item.Tag != null)
                {
                    Document d = item.Tag as Document;

                    switch (d.Type)
                    {
                        case Document.DocumentType.Spreadsheet:
                            rTFMenuItem.Visible = false;
                            cSVMenuItem.Visible = true;
                            break;
                        case Document.DocumentType.Document:
                            rTFMenuItem.Visible = true;
                            cSVMenuItem.Visible = false;
                            break;
                        default:
                            rTFMenuItem.Visible = false;
                            cSVMenuItem.Visible = false;
                            break;
                    }
                }
            }
        }

        private void pDFMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            exportFileDialog.FileName = d.DocumentEntry.Title.Text;
            var type = Document.DownloadType.pdf;
            exportFileDialog.Filter = "PDF文件|*.pdf";
            if (exportFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = exportFileDialog.OpenFile();
                exportFile(stream, file);
            }
        }

        private void exportFile(Stream stream, Stream file)
        {
            try
            {
                if (file != null)
                {
                    int nBytes = 2048;
                    int count = 0;
                    Byte[] arr = new Byte[nBytes];

                    do
                    {
                        count = stream.Read(arr, 0, nBytes);
                        file.Write(arr, 0, count);
                    } while (count > 0);
                    file.Flush();
                    file.Close();
                }
                stream.Close();
                MessageBox.Show("下载成功", "转换完成", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败：" + ex.Message, "转换失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        private void hTMLMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            exportFileDialog.FileName = d.DocumentEntry.Title.Text;
            var type = Document.DownloadType.html;
            exportFileDialog.Filter = "HTML文件|*.html";
            if (exportFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = exportFileDialog.OpenFile();
                exportFile(stream, file);
            }
        }

        private void tXTMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            exportFileDialog.FileName = d.DocumentEntry.Title.Text;
            var type = Document.DownloadType.txt;
            exportFileDialog.Filter = "TXT文件|*.txt";
            if (exportFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = exportFileDialog.OpenFile();
                exportFile(stream, file);
            }
        }

        private void rTFMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            exportFileDialog.FileName = d.DocumentEntry.Title.Text;
            var type = Document.DownloadType.rtf;
            exportFileDialog.Filter = "RTF文件|*.rtf";
            if (exportFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = exportFileDialog.OpenFile();
                exportFile(stream, file);
            }
        }

        private void cSVMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            exportFileDialog.FileName = d.DocumentEntry.Title.Text;
            var type = Document.DownloadType.csv;
            exportFileDialog.Filter = "CSV文件|*.csv";
            if (exportFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = exportFileDialog.OpenFile();
                exportFile(stream, file);
            }
        }

        private void openfileLocalMenuItem_Click(object sender, EventArgs e)
        {
            ListViewItem item = listView1.FocusedItem;
            Document d = item.Tag as Document;
            Process.Start("WINWORD.EXE", d.DocumentEntry.AlternateUri.ToString());
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //pptquery.Starred = true;
            //DocumentsFeed pptfeed = lf.m.request.Service.Query(pptquery);
            //DocumentsFeed exlfeed = lf.m.request.Service.Query(exlquery);
            string cat = listBox1.SelectedItem.ToString();
            Feed<Document> feeds = lf.m.request.GetEverything();
            switch (cat)
            {
                case "所有文件":
                    UpdateDocList();
                    break;

                case "所有WORD文件":
                    listView1.Items.Clear();
                    foreach (Document entry in feeds.Entries)
                    {
                        if (entry.DocumentEntry.IsDocument)
                        {
                            ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text,
                                                                 "icon_9_document_list.png");
                            item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                            item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                            item.SubItems.Add(entry.Author);
                            item.Tag = entry;
                            listView1.Items.Add(item);
                        }
                    }
                    break;

                case "所有PPT文件":
                    listView1.Items.Clear();
                    foreach (Document entry in feeds.Entries)
                    {
                        if (entry.DocumentEntry.IsPresentation)
                        {
                            ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text,
                                                                 "icon_9_presentation_list.png");
                            item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                            item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                            item.SubItems.Add(entry.Author);
                            item.Tag = entry;
                            listView1.Items.Add(item);
                        }
                    }
                    break;

                case "所有EXCEL文件":
                    listView1.Items.Clear();
                    foreach (Document entry in feeds.Entries)
                    {
                        if (entry.DocumentEntry.IsSpreadsheet)
                        {
                            ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text,
                                                                 "icon_9_spreadsheet_list.png");
                            item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                            item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                            item.SubItems.Add(entry.Author);
                            item.Tag = entry;
                            listView1.Items.Add(item);
                        }
                    }
                    break;

                case "我的文件":
                    listView1.Items.Clear();

                    foreach (Document entry in feeds.Entries)
                    {
                        if (entry.Author == lf.m.request.Settings.Credentials.Username && !entry.DocumentEntry.IsFolder)
                        {
                            ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                            item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                            item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                            item.SubItems.Add(entry.Author);
                            item.Tag = entry;
                            listView1.Items.Add(item);
                        }
                    }
                    break;

                case "共享给我的文件":
                    listView1.Items.Clear();

                    foreach (Document entry in feeds.Entries)
                    {
                        if (entry.Author != lf.m.request.Settings.Credentials.Username && !entry.DocumentEntry.IsFolder)
                        {
                            ListViewItem item = new ListViewItem(entry.DocumentEntry.Title.Text, docimage(entry));
                            item.SubItems.Add(entry.DocumentEntry.Published.ToString());
                            item.SubItems.Add(entry.DocumentEntry.Updated.ToString());
                            item.SubItems.Add(entry.Author);
                            item.Tag = entry;
                            listView1.Items.Add(item);
                        }
                    }
                    break;
            }
            //DocumentsFeed wordfeed = lf.m.request.Service.Query(wordquery);
            //foreach (DocumentEntry d in wordfeed.Entries)
            //{
            //    string imageKey = "";
            //    if (d.IsDocument)
            //    {
            //        imageKey = "icon_9_document_list.png";
            //    }
            //    else if (d.IsSpreadsheet)
            //    {
            //        imageKey = "icon_9_spreadsheet_list.png";
            //    }
            //    else if (d.IsPresentation)
            //    {
            //        imageKey = "icon_9_presentation_list.png";
            //    }
            //    else
            //    {
            //        imageKey = "icon_9_form_list.png";
            //    }

            //    ListViewItem item = new ListViewItem(d.Title.Text, imageKey);
            //    item.SubItems.Add(d.Updated.ToString());
            //    item.SubItems.Add(d.LastModified.Name);
            //    listView1.Items.Add(item);
            //}
            //break;
        }

        private void uploadButton_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            openFileUpload.ShowDialog();
            string filename = openFileUpload.FileName;

            if (filename == "")
            {
                MessageBox.Show("未选择文件", "未上传", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            lf.m.service.UploadDocument(filename, null);
            UpdateDocList();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            UpdateDocList();
        }

        private void logoutButton_Click(object sender, EventArgs e)
        {
            lf.m.Logout();
            listBox1.Enabled = false;
            loginMenuItem.Enabled = true;
            logoutMenuItem.Enabled = false;
            listView1.Items.Clear();
            listView1.Columns.Clear();
            FoldertreeView.Nodes.Clear();
            loginButton.Visible = true;
            logoutButton.Visible = false;
            toolStripStatusLabel1.Text = "未登录";
        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            DialogResult r = lf.ShowDialog();

            if (r == DialogResult.OK)
            {
                listBox1.Enabled = true;
                loginMenuItem.Enabled = false;
                logoutMenuItem.Enabled = true;
                UpdateDocList();
                loginButton.Visible = false;
                logoutButton.Visible = true;
                toolStripStatusLabel1.Text = "已登录";
            }
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void downloadButton_ButtonClick(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择下载文件", "请选择", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ListViewItem items = listView1.SelectedItems[0];

            Document d = items.Tag as Document;
            saveFileDownload.FileName = d.DocumentEntry.Title.Text;

            Document.DownloadType type;

            switch (d.Type)
            {
                case Document.DocumentType.Presentation:
                    saveFileDownload.Filter = "Powerpoint|*.ppt";
                    type = Document.DownloadType.ppt;
                    break;
                case Document.DocumentType.Spreadsheet:
                    saveFileDownload.Filter = "Excel|*.xls";
                    type = Document.DownloadType.xls;
                    break;
                default:
                    saveFileDownload.Filter = "Microsoft Word|*.doc";
                    type = Document.DownloadType.doc;
                    break;
            }

            if (saveFileDownload.ShowDialog() == DialogResult.OK)
            {
                Stream stream = lf.m.request.Download(d, type);
                Stream file = saveFileDownload.OpenFile();

                try
                {
                    if (file != null)
                    {
                        int nBytes = 2048;
                        int count = 0;
                        Byte[] arr = new Byte[nBytes];

                        do
                        {
                            count = stream.Read(arr, 0, nBytes);
                            file.Write(arr, 0, count);
                        } while (count > 0);
                        file.Flush();
                        file.Close();
                    }
                    stream.Close();
                    MessageBox.Show("下载成功", "下载完成", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("下载失败：" + ex.Message, "下载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw;
                }
            }
        }

        private void openButton_Click(object sender, EventArgs e)
        {
            if (!lf.m.loggedIn)
            {
                MessageBox.Show("请先登录", "未登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (listView1.SelectedItems.Count > 0)
            {
                Document entry = (Document) listView1.SelectedItems[0].Tag;
                Process.Start(entry.DocumentEntry.AlternateUri.ToString());
            }
            else
            {
                MessageBox.Show("请选择打开文件", "请选择", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void helpButton_Click(object sender, EventArgs e)
        {
            Process.Start("https://code.google.com/p/my-google-doc-online/");
        }

        private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                MessageBox.Show("listView1.SelectedItems.Count<=0");
                return;
            }

            IList<ListViewItem> dragItemList = new List<ListViewItem>();

            foreach (ListViewItem lvi in listView1.SelectedItems)
            {
                dragItemList.Add(lvi);
            }


            //对控件中的项目集合开始拖放操作
            listView1.DoDragDrop(dragItemList, DragDropEffects.Move);
        }

        private void FoldertreeView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof (TreeNode)) || e.Data.GetDataPresent(typeof (List<ListViewItem>)))
                e.Effect = DragDropEffects.Move;
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void FoldertreeView_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof (List<ListViewItem>)))
            {
                //TreeNode dragNode = (TreeNode)(listView1.Tag);

                //获取被拖动列表项目数据
                IList<ListViewItem> dragItemList = (IList<ListViewItem>) (e.Data.GetData(typeof (List<ListViewItem>)));
                Point po = new Point(e.X, e.Y);
                // Position.X = ;
                //Position.Y = e.Y;
                Point po1 = FoldertreeView.PointToClient(po);

                //获取拖动目标树节点
                TreeNode dropNode = this.FoldertreeView.GetNodeAt(po1);

                //TreeNode dropNode = this.FoldertreeView.GetNodeAt(e.X, e.Y);

                Document child = dragItemList[0].Tag as Document;
                Document parent = dropNode.Tag as Document;
                try
                {
                    lf.m.request.MoveDocumentTo(parent, child);
                }
                catch (Exception)
                {
                    MessageBox.Show("无法移动！");
                    return;
                }


                UpdateDocList();
            }
        }

        //if (cat == listBox1.Items.ToString())
        //{

        //}
    }
}